package com.pym.content.service.impl;

import com.pym.content.mapper.CourseCategoryMapper;
import com.pym.content.model.dto.CourseCategoryTreeDto;
import com.pym.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {

        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
//定义一个list作为为最终要返回的数据
        List<CourseCategoryTreeDto> categoryTreeDtos=new ArrayList<>();
        //为了方便找子节点的父节点,定义一个map
        HashMap<String,CourseCategoryTreeDto> nodeMap = new HashMap<>();
        courseCategoryTreeDtos.stream().forEach(item->{
                if(item.getParentid().equals(id)){
                    categoryTreeDtos.add(item);
                }
                //找到该节点的父节点
            String parentid = item.getParentid();
                    //找到该节点的父节点对象
                CourseCategoryTreeDto parentNode = nodeMap.get(parentid);

            if (parentNode!=null){
                List childrenTreeNodes = parentNode.getChildrenTreeNodes();
                 if (childrenTreeNodes==null){
                     parentNode.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                 }
                //找到子节点,放到他的父节点childrenTreeNode
                parentNode.getChildrenTreeNodes().add(item);

            }

        });
        return   categoryTreeDtos;

    }
}
